from models import *

__all__ = ('TagsProperty',)

def curry(_curried_func, *args, **kwargs):
    def _curried(*moreargs, **morekwargs):
        return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
    return _curried


def get_FIELD_objects(obj, field):
    tag_keys = getattr(obj, field.name)
    if len(tag_keys):
        return Tag.get(tag_keys)
    return []

def get_FIELD_str(obj, field):
    return ', '.join([t.name for t in get_FIELD_objects(obj, field)])



class TagsProperty(db.ListProperty):
    def __init__(self, **kwds):
        super(TagsProperty, self).__init__(item_type=db.Key, **kwds)
    
    def __set__(self, model_instance, value):
        if isinstance(value, str) or isinstance(value, unicode):
            set_val = []
            words = set([w.strip() for w in value.split(',')])
            for name in words:
                if len(name) > 0:
                    set_val.append(Tag.get_key(name))
        else:
            set_val = value
        super(TagsProperty, self).__set__(model_instance, set_val)
    
    def __property_config__(self, model_class, property_name):
        super(TagsProperty, self).__property_config__(model_class, property_name)
        
        setattr(model_class, 'get_%s_str' % property_name, curry(get_FIELD_str, field=self))
        setattr(model_class, 'get_%s_objects' % property_name, curry(get_FIELD_objects, field=self))

